//
//  HistorySteps.m
//  MinusTheBox
//
//  Created by Chi Ho Chiu on 15/4/12.
//  Copyright 2012 Individual. All rights reserved.
//

#import "HistorySteps.h"

@implementation HistorySteps
@synthesize historyStepArray;

-(void) dealloc
{
	[historyStepArray release];
	[super dealloc];
}

-(id) initWithFirstStep:(Box2DArray *)array
{
	if( self = [super init] )
	{
		//Alloc historyStepArray
		NSMutableArray *arr = [[NSMutableArray alloc] init];
		self.historyStepArray = arr;
		[arr release];
		
		[self addNewStep:array];

	}
	
	return self;
}

-(void) removeLastStep
{
	[historyStepArray removeLastObject];
}

-(void) addNewStep:(Box2DArray *)array
{
	Box2DArray *arr = [Box2DArray node];	//Create a new Box2DArray
	for(int col = 0; col < MAX_BOX_COLUMN; col++)
	{
		for(int row = 0; row < MAX_BOX_ROW; row++)
		{
			id obj = [array getObjectInColumn:col row:row];
			if(obj != [NSNull null])
			{
				[arr addObjectInColumn:col row:row value:[obj copy]];
			}
		}
	}

	[historyStepArray addObject:arr];	//Add to History Step

}

-(Box2DArray *) getPreviousStep
{
	//count - 1 = Current, count - 2 =  Previous
	NSInteger previousStepIndex = historyStepArray.count - 2;
	
	if(previousStepIndex >= 0)
	{
		//Get the history Box2DArray
		Box2DArray *array = (Box2DArray *)[historyStepArray objectAtIndex:previousStepIndex];
		
		//Create a new Box2DArray and return it
		Box2DArray *arr = [Box2DArray node];
		for(int col = 0; col < MAX_BOX_COLUMN; col++)
		{
			for(int row = 0; row < MAX_BOX_ROW; row++)
			{
				id obj = [array getObjectInColumn:col row:row];
				if(obj != [NSNull null])
				{
					[arr addObjectInColumn:col row:row value:[obj copy]];
				}
			
			}
		}
		
		return arr;
	}
		
	return nil;	//Return nil if Previous Step doesn't existed
}

@end
